$(function() {
    var cols=6;
	var rows_delete=0;
	var mode="add";
	var m_id=0;
    var url='controls/group_model.php';
	if (_dd==1){
	$("#btnAdd").show();
	}else{
		$("#btnAdd").hide();
	}
    LoadData();
	
	$("#btnAdd").live('click', function(){
		$("#txtName").val("");
		mode="add";
		load_all(0)
	});
	function load_all(id){
		load_permission(id, $("#table_master"),"MA");
		load_permission(id, $("#table_student"),"ST");
		load_permission(id, $("#table_employee"),"EP");
		load_permission(id, $("#table_service"),"SE");
		load_permission(id, $("#table_stock"),"SO");
		load_permission(id, $("#table_account"),"AC");
		load_permission(id, $("#table_report"),"RE");
	}
	function load_permission(id,table,type){
		 table.dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": false,
            "bPaginate": false,
            "bLengthChange": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "load_detail"},
							{"name": "id", "value": id},  
							{"name": "type", "value":type}
				);
            },
            "aoColumnDefs": [
				{"bVisible": false, "aTargets": [1]},
                {"bSortable": true, "aTargets": [2], "sClass": "text-left"},
                { "bSortable": false, "aTargets": [3],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
						var html="&nbsp;";
						if (full[8]==1){
							if (full[3]==1)
								html= "<input type='checkbox'  name='view' value='1' checked />";
							else 
								html= "<input type='checkbox'  name='view' value='1' />";
							}
						return html;
					}
				},
               { "bSortable": false, "aTargets": [4],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
						var html="&nbsp;";
						if (full[9]==1){
							if (full[4]==1)
								html= "<input type='checkbox'  name='add' value='1' checked />";
							else 
								html= "<input type='checkbox'  name='add' value='1'  />";
						}
						return html;
					}
				
				},
			  { "bSortable": false, "aTargets": [5],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
						var html="&nbsp;";
					if (full[10]==1){
						if (full[5]==1)
							html= "<input type='checkbox'  name='edit' value='1' checked />";
						else 
                            html="<input type='checkbox'  name='edit' value='1' />";
						}
						return html;
					}
					
				},
                { "bSortable": false, "aTargets": [6],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
						var html="&nbsp;";
						if(full[11]==1){
							if (full[6]==1)
								html= "<input type='checkbox'  name='del' value='1'  checked/>";
							else 
								html=  "<input type='checkbox'  name='del' value='1'  />";
						}
						return html;
					}
				
				},
				{ "bSortable": false, "aTargets": [7],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
						var html="&nbsp;";
						if(full[12]==1){
							if (full[7]==1)
								html= "<input type='checkbox'  name='approve' value='1'  checked/>";
							else 
								html=  "<input type='checkbox'  name='approve' value='1'  />";
						}
						return html;
					}
				
				},
				{  "bVisible": false , "aTargets": [ 8 ] },	
				{  "bVisible": false , "aTargets": [ 9 ] },	
				{  "bVisible": false , "aTargets": [ 10 ] },	
				{  "bVisible": false , "aTargets": [ 11 ] },	
				{  "bVisible": false , "aTargets": [ 12 ] },	

            ], "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }

        });
	}
	//Popup confirm delete
	$("#btnDelete").live('click', function(){
		var row_id =$('#resultData').dataTable().fnGetData(rows_delete);
		var id=row_id[1];
		 $.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"del","id":id},
				 success: function(data){
					$("#popupConfirm").modal('hide');
					$('#resultData').dataTable().fnDeleteRow( rows_delete );
					$('#resultData').dataTable().fnDraw();
				 }
			 });
 
	}); 
	$(".btnEdit").live('click',function(){
		mode="edit";
		var rows = $('#resultData').dataTable().fnGetPosition($(this).closest("tr").get(0));
		var data =$('#resultData').dataTable().fnGetData(rows);
		 
		m_id = data[1];
		load_all(m_id);
		$("#txtName").val(data[2]);
		if (data[3]=='Y'){
			$("#chkY").attr('checked','checked');
		}else{
			$("#chkN").attr('checked','checked');
		}
	});
	$("#btnSave").live('click',function(){
		$("#txtName").jqBootstrapValidation({preventSubmit: false,
		submitSuccess: function ($form, event) { event.preventDefault();}
		}); 
		
	 	var detail_table= $('#table_master,#table_student ,#table_employee ,#table_service'); 
		var _name = $.trim($("#txtName").val());
		
		var list = [];
		list = getPermissionValue(); 
	    
		var dataSet;
		 
		if (mode=="add"){
			dataSet={"m":"add","name":_name,"list":list,"status":$('input[name=chk]:checked').val()};  
		}else{
			dataSet={"m":"edit","id":m_id,"name":_name,"list":list,"status":$('input[name=chk]:checked').val()};  
		}
		
		if (_name!=""){
			$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: dataSet,
				success: function(data){
				 
					$("#popup").modal('hide');
					LoadData();
				}
			});
			
		}
		 $("#txtName").jqBootstrapValidation("destroy");
	});
	
	function getPermissionValue(){
		var list = [];
		var table ;
		$('.table').each(function(){
			table = $(this).dataTable()
			table.$('tbody tr').each(function() {
				var userData =table.fnGetData(this);
				var	add =isNaN($(this).find("input[name=add]:checked").val())?'0':'1';
				var	edit = isNaN($(this).find("input[name=edit]:checked").val())?'0':'1';   
				var	del = isNaN($(this).find("input[name=del]:checked").val())?'0':'1';   
				var	view = isNaN($(this).find("input[name=view]:checked").val())?'0':'1';  
				var approve = isNaN($(this).find("input[name=approve]:checked").val())?'0':'1';  
				list.push({'sid':userData[1],
							'a': add,
							'v': view,
							'e': edit,
							'd': del,
							'col1': approve
							});
		 
			});
		});
		return list;
	}
	$(".btnDel").live('click',function(){
		 
		var rows = $(this).closest("tr").get(0);
		rows_delete = $('#resultData').dataTable().fnGetPosition(rows);
 
	});
	
	$("#btnPrintDraft").click(function(){
	  $("#resultData").printThis();
		return false;
           
	});	
	
    function LoadData(){
        $( "#resultData tbody tr" ).remove();
 
        $('#resultData').dataTable( {
			"bProcessing": true,
			"bFilter": false,
			"bLengthChange": false,
			"sAjaxSource": url,
			"oLanguage": {
				"sEmptyTable":     "ไม่พบข้อมูล"
			},
			"bDestroy": true,
			"sServerMethod": "POST",
			"fnServerParams": function ( aoData ) {
					aoData.push( { "name": "m", "value": "load" } );
				},
			"aoColumnDefs":[
				{  "bVisible": false , "aTargets": [ 1 ] },	
				{   "bSortable": true, "aTargets": [ 2 ] },	
				{   "bSortable": true, "aTargets": [ 3 ], "sClass":"center",
					"mRender": function ( data, type, full ) {
						var tmp="";
						if (data=='Y')
							tmp="<font style='color:green !important;'>ใช้งาน</font>";
						else
							tmp="<font style='color:red !important;'>ยกเลิก</font>";
						return tmp;}
				},
				{ "aTargets": [ 4 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
						if (_it==1)
							return "<a href='#popup' data-toggle='modal'><img src='img/edit-file.png' class='btnEdit' style='cursor:pointer;'/></a>";
						else
							return "";
					}
				},
				{"aTargets": [ 5 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
						if (_te==1)
							return "<a href='#popupConfirm' data-toggle='modal'><img src='img/delete-file.png' class='btnDel' style='cursor:pointer;'/></a>";
						else
							return "";
					}
				}
			],"fnDrawCallback": function ( oSettings ) {
				 
			/* Need to redo the counters if filtered or sorted */
			     var oSettings = this.fnSettings();
                 var iTotalRecords = oSettings.fnRecordsTotal();
				//alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);
				 
					if (iTotalRecords > 0){ 	
						if ( oSettings.bSorted || oSettings.bFiltered )
						{
							for ( var i=0, iLen=iTotalRecords ; i<iLen ; i++ )
							{
								$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
							}
						}
					}
					 
				} 
		 } );
		 
      }
    
});


